#include <iostream>
#include <string>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>

using namespace std;

void usage(string proc)
{
    cout << "Usage:\n\t" << proc << " local_port\n"
         << endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        usage(argv[0]);
        exit(1);
    }
    string serverip = argv[1];
    uint16_t port = stoi(argv[2]);
    // 同样的创建套接字----->用来发消息
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        exit(2);
    }
    // tcp client 要bind，不要显示的bind.
    struct sockaddr_in server;
    // 构建目标主机的socket信息
    memset(&server, 0, sizeof(server)); // 用来初始化
    server.sin_port =htons(port);//将网络地址转化为主机地址
    server.sin_addr.s_addr = inet_addr(serverip.c_str()); // ip地址
    server.sin_family = AF_INET;

    // 连接
    int n = connect(sockfd, (sockaddr *)&server, sizeof(server));
    if (n < 0)
    {
        cout << "connet error! " << endl;
        exit(3);
    }

    // 初始化完成
    while (1)
    {
        cout << "Place Enter#: ";
        string outmessage;
        getline(cin, outmessage);
        ssize_t s = send(sockfd, outmessage.c_str(), outmessage.size(), 0); // 发消息给服务端
        if (s > 0)
        {
            char inbuffer[1024];
            ssize_t m = recv(sockfd, inbuffer, sizeof(inbuffer) - 1, 0);//echo 消息
            if (m > 0)
            {
                inbuffer[m] = 0;
                cout << inbuffer << endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }
    close(sockfd);
    return 0;
}